<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;

use App\Model\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Resources\AdminResource;

class AdminController extends Controller
{

    /**
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        $models = User::query()->paginate();
        return AdminResource::collection($models);
    }

    /**
     * @param Request $request
     * @return AdminResource
     */
    public function store(Request $request)
    {
        $model = new User();
        $data = $request->all();
        $data['password'] = bcrypt($data['password']);
        $model->fill($data);
        $model->save();
        return new AdminResource($model);
    }

    /**
     * @param Request $request
     * @param $id
     * @return AdminResource
     */
    public function update(Request $request, $id)
    {
        $data = $request->all();
        if (!empty($data['password'])) {
            $data['password'] = bcrypt($data['password']);
        }
        $model = $this->findModel($id);
        $model->fill($data);
        $model->save();
        return new AdminResource($model);
    }

    /**
     * @param $id
     * @return AdminResource
     */
    public function show($id)
    {
        return new AdminResource($this->findModel($id));
    }

    /**
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        return response()->json($this->admin->destroy($id));
    }

    /**
     * @param $id
     * @return mixed
     */
    public function findModel($id){
        return User::query()->where('id',$id)->first();
    }
    /**
     * 获取当前登录用户信息
     * @return mixed
     */
    public function getProfile()
    {
        $authUser = Auth::user();
        return new AdminResource($authUser);
    }

    /**
     * @param $id
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function resetPassword($id, Request $request)
    {
        $model = $this->findModel($id);
        $data = $request->all();
        if (!empty($data['password'])) {
            $data['password'] = bcrypt($data['password']);
        }
        $model->fill($data);
        $model->save();
        return new AdminResource($model);
    }
}
